package zkk.com.mengqu.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import zkk.com.mengqu.R;
import zkk.com.mengqu.adapter.FamilyFoodAdapter;
import zkk.com.mengqu.fragment.FamilyFoodFragment;
import zkk.com.mengqu.fragment.FoodCommentFragment;
import zkk.com.mengqu.manager.APIManager;
import zkk.com.mengqu.models.Food;
import zkk.com.mengqu.models.Kitchen;
import zkk.com.mengqu.models.KitchenDetail;
import zkk.com.mengqu.simplepreferences.Share;
import zkk.com.mengqu.util.FinalString;

/**
 * Created by Administrator on 2017/4/13.
 */
public class KitchenActivity extends FragmentActivity implements View.OnClickListener{
    private Context context;
    public static TextView shopCount;//购买数量

    private TextView txAllPrice, makeOrder, kitchenName, kitchenAddress;//总价,结算.厨房名字，厨房地址
    private ImageView star1, star2, star3, star4, star5;//星级
    private ImageView back, shoppingCar;//返回,购物车
    private List<Fragment> mFragmentList = new ArrayList<>();
    private TabLayout tableLayout;//导航栏
    private ViewPager viewPager;
    private ApnFragmentAdapter mAdapter;
    //记录添加到购物车的商品信息
    private Map<Integer,Food> foodMap = FinalString.foodMap;
//g
    private int allPrice = 0;//总价
    private int kid;//厨房id
//
    public Handler messageHandler = new Handler(){
        public void handleMessage(Message msg) {
            //添加商品
            if (msg.what == FinalString.CASE_SHOPPING_CAR_ADD) {
                Bundle bundle = msg.getData();
                Log.w("add" ,"name:"+bundle.getString("food"));
                Food food = new Food(bundle.getString("food"));
                shopCount.setText("" + add(food));
                txAllPrice.setText("" + allPrice);
            }
            //删除商品
            if (msg.what == FinalString.CASE_SHOPPING_CAR_SUBTRACT) {
                Bundle bundle = msg.getData();
                Log.w("subtract" ,"name:"+bundle.getString("food"));
                Food food = new Food(bundle.getString("food"));
                shopCount.setText("" + subtract(food));
                txAllPrice.setText("" + allPrice);
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_kitchen);
        context = getApplicationContext();
        initView();
        getKitchen(kid);
    }

    @Override
    protected void onResume() {
        super.onResume();
        FamilyFoodAdapter.parentHandler = messageHandler;
    }

    public void initView(){
        kid = getIntent().getIntExtra("kid",0);
        back = (ImageView)findViewById(R.id.iv_back);
        shoppingCar = (ImageView)findViewById(R.id.iv_shopping_car);
        shopCount = (TextView) findViewById(R.id.tx_shop_count);
        txAllPrice = (TextView) findViewById(R.id.tx_prices);
        makeOrder = (TextView) findViewById(R.id.tx_buy);
        kitchenName = (TextView) findViewById(R.id.tx_kitchen_name);
        kitchenAddress = (TextView) findViewById(R.id.tx_kitchen_address);

        star1 = (ImageView)findViewById(R.id.iv_score_star_1);
        star2 = (ImageView)findViewById(R.id.iv_score_star_2);
        star3 = (ImageView)findViewById(R.id.iv_score_star_3);
        star4 = (ImageView)findViewById(R.id.iv_score_star_4);
        star5 = (ImageView)findViewById(R.id.iv_score_star_5);

        back.setOnClickListener(this);
        shoppingCar.setOnClickListener(this);
        makeOrder.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.iv_back:
                finish();
                FinalString.foodMap.clear();
                break;
            case R.id.iv_shopping_car:
                Toast.makeText(context , "购物车" , Toast.LENGTH_LONG).show();
                startActivity(new Intent(this , SubmitOrderActivity1.class));
                break;
            case R.id.tx_buy:
                Toast.makeText(context , "结算" , Toast.LENGTH_LONG).show();
//                for (Food deshesList : FinalString.foodMap.values()) {
//                    Log.w("foodmap","" + deshesList.toString());
//                }

                if (!"null".equals(Share.getUserPhone())){
                    Intent intent = new Intent(this , SubmitOrderActivity.class);
                    intent.putExtra("allPrice","" + allPrice);
                    startActivity(intent);
                }else {
                    startActivity(new Intent(KitchenActivity.this , LoginCodeActivity.class));
                }

                break;
            default:
                break;
        }
    }

    //显示星级
    public void setScore(int score){
        switch (score){
            case 1:
                star1.setVisibility(View.VISIBLE);
                break;
            case 2:
                star1.setVisibility(View.VISIBLE);
                star2.setVisibility(View.VISIBLE);
                break;
            case 3:
                star1.setVisibility(View.VISIBLE);
                star2.setVisibility(View.VISIBLE);
                star3.setVisibility(View.VISIBLE);
                break;
            case 4:
                star1.setVisibility(View.VISIBLE);
                star2.setVisibility(View.VISIBLE);
                star3.setVisibility(View.VISIBLE);
                star4.setVisibility(View.VISIBLE);
                break;
            case 5:
                star1.setVisibility(View.VISIBLE);
                star2.setVisibility(View.VISIBLE);
                star3.setVisibility(View.VISIBLE);
                star4.setVisibility(View.VISIBLE);
                star5.setVisibility(View.VISIBLE);
                break;
        }
    }

    //添加商品
    public int add(Food food){
        int allCount = 0;
        int id = food.getId();
        Log.w("id",""+id);
        if (foodMap.containsKey(id)){
            Food food1 = foodMap.get(id);
            int count = food1.getCount();
            Log.w("count",""+count);
            food1.setCount(++count);
            foodMap.put(id,food1);
        }else {
            food.setCount(1);
            foodMap.put(id,food);
        }
        //计算总数量.
        for (Food deshesList : foodMap.values()) {
            Log.w("foodmap","" + deshesList.toString());
            allCount += deshesList.getCount();
        }

        //计算总价
        allPrice = 0;
        for (int fid : foodMap.keySet()){
//            Log.w("foodMap",foodMap.get(key)[0]+","+foodMap.get(key)[1]);
            allPrice += foodMap.get(fid).getPrice() * foodMap.get(fid).getCount();
        }
        Log.w("allPrice", ""+allPrice);
        return allCount;
    }

    //删除商品
    public int subtract(Food food){
        int allCount = 0;
        int id = food.getId();
        Log.w("id",""+id);
        if (foodMap.containsKey(id)){
            if (foodMap.get(id).getCount() <= 0){
                foodMap.remove(id);
            }else{
                Food food1 = foodMap.get(id);
                int count = food1.getCount();
                food1.setCount(--count);
                foodMap.put(id, food1);
            }
        }
        for (Food deshesList : foodMap.values()) {
            allCount += deshesList.getCount();
        }
        allPrice =0;
        for (int fid : foodMap.keySet()){
            allPrice += foodMap.get(fid).getCount() * foodMap.get(fid).getPrice();
        }
        Log.w("allPrice", ""+allPrice);
        return allCount;
    }

    //设置tableLayout
    public void setTableLayout(Bundle bundle){
        tableLayout = (TabLayout)findViewById(R.id.tableLayout);
        viewPager = (ViewPager)findViewById(R.id.viewPager);

        FamilyFoodFragment fragment = new FamilyFoodFragment();
        fragment.setArguments(bundle);
        mFragmentList.add(fragment);//住家菜品
        mFragmentList.add(new FoodCommentFragment());//菜品评价

        mAdapter = new ApnFragmentAdapter(getSupportFragmentManager());
        viewPager.setAdapter(mAdapter);
        tableLayout.setupWithViewPager(viewPager);
        tableLayout.setTabMode(TabLayout.MODE_FIXED);
    }

    //获取指定id的厨房信息
    public void getKitchen(final int kid){
        APIManager.setManager()
//                .getKitchen("kitchen_detail",kid)
                .getKitchen(kid)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<KitchenDetail>() {
                    @Override
                    public void onCompleted() {
                        Log.w("onCompleted","onCompleted");
                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.w("onError","onError");
                        e.printStackTrace();
                    }

                    @Override
                    public void onNext(KitchenDetail kitchen) {
                        Log.w("Kid------" , "" + kitchen.getName());
                        Log.w("Kid------" , "" + kitchen.getName());
                        kitchenName.setText("" + kitchen.getName());
                        kitchenAddress.setText("" + kitchen.getAddr());
                        setScore(kitchen.getScore());
                        Bundle bundle = new Bundle();
                        bundle.putInt("kid", kitchen.getId());
                        setTableLayout(bundle);
                    }
                });
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
			FinalString.foodMap.clear();
            finish();
            return true;
        }
        // 拦截MENU按钮点击事件，让他无任何操作
        if (keyCode == KeyEvent.KEYCODE_MENU) {
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private class ApnFragmentAdapter extends FragmentPagerAdapter {
        CharSequence[] TITLE = new CharSequence[]{"住家菜品","菜品评价"};

        public ApnFragmentAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            return mFragmentList.get(position);
        }

        @Override
        public int getCount() {
            return TITLE.length;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return TITLE[position];
        }
    }
}
